<template>
  <div class="setting-approve">
    <el-radio-group class="approve-radio-group" v-model="approveSetting.level" @change="switchLevel">
      <el-radio :label="1" class="ml-12">{{$t('common.base.approveLevel', {data1:$t('common.base.number1')})}}</el-radio>
      <el-radio :label="2" class="ml-12">{{$t('common.base.approveLevel', {data1:$t('common.base.number2')})}}</el-radio>
    </el-radio-group>
    <div v-if="approveSetting.level >= 1" class="setting-approve-people">
      <!--S 一级审批设置 -->
      <div class="one-level-approve">{{$t('common.form.setting.approveSetting.des1')}}{{ approveSetting.level > 1 ? $t('common.base.approveLevelUser', {data1:$t('common.base.number1')}) : $t('common.base.approveUser') }}</div>
      <el-tooltip :disabled="!approveSetting.leader || options.some(opt => approveSetting.leader === opt.value)" :content="$t('common.form.setting.approveSetting.des2')">
        <el-select
          class="w-187"
          v-model="approveSetting.leader"
          :placeholder="$t('common.placeholder.select')"
          @change="(val) => updateApproveSetting('leader', val, 1)"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-tooltip>
      <template v-if="approveSetting.leader === 'users'" class="mt-12">
        <el-input
          v-if="!isOpenData"
          class="w-187"
          :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})"
          readonly
          :value="getApproverNames(approveSetting.approves)"
          @click.native="selectApproveUser(1)"
        />
        <div v-else class="setting-open-data-input block-inline w-187" @click="selectApproveUser(1)">
          <template v-if="!approveSetting.approvers || !approveSetting.approvers.length"><span class="placeholder-text">{{$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})}}</span></template>
          <template v-else v-for="(item, index) in getApproverIds(approveSetting.approvers)">
            <open-data :key="item" type="userName" :openid="item"></open-data>
            <ui-separator :index="index" :list="getApproverIds(approveSetting.approvers)" :key="`${item}${uuid()}`" />
          </template>
        </div>
        
        <!-- <el-button class="ml-12" type="primary" size="small" @click="selectApproveUser(1)">添加审批人</el-button> -->
      </template>
      <!--E 一级审批设置 -->
      <!--S 二级以上审批设置 -->
      <template v-if="approveSetting.level > 1">
        <span
          v-for="(setting, idx) in approveSetting.multiApproveSetting"
          :key="idx"
          class="setting-approve-people"
        >
        <div class="more-level-approve">{{$t('common.base.approveLevelUser', {data1:formatNumToCN((idx + 2))})}}</div>
          <el-tooltip :disabled="!approveSetting.multiApproveSetting[idx].leader || options.some(opt => approveSetting.multiApproveSetting[idx].leader === opt.value)" :content="$t('common.form.setting.approveSetting.des2')">
            <el-select
              class="w-187"
              v-model="setting.leader"
              :placeholder="$t('common.placeholder.select')"
              @change="(val) => updateApproveSetting('leader', val, idx + 2)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-tooltip>
          <template v-if="setting.leader === 'users'">
            <el-input
              v-if="!isOpenData"
              class="w-187 mt-12"
              :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})"
              readonly
              :value="getApproverNames(setting.approves)"
              @click.native="selectApproveUser(idx + 2)"
            />
            <div v-else class="setting-open-data-input block-inline w-187" @click="selectApproveUser(idx + 2)">
              <template v-if="!approveSetting.approvers || !approveSetting.approvers.length"><span class="placeholder-text">{{$t('common.placeholder.selectSomething', {0:$t('common.base.approveUser')})}}</span></template>
              <template v-else v-for="(item, index) in getApproverIds(approveSetting.approvers)">
                <open-data :key="item" type="userName" :openid="item"></open-data>
                <ui-separator :index="index" :list="getApproverIds(approveSetting.approvers)" :key="`${item}${uuid()}`" />
              </template>
              <!-- <open-data v-for="staffId in getApproverIds(setting.approvers)" :key="staffId" type="userName" :openid="staffId"></open-data> -->
            </div>
          </template>
        </span>
      </template>
      <!--E 二级以上审批设置 -->
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import _ from 'lodash';
import TaskApprover from '@model/types/setting/task/TaskApprover';

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'

export default {
  name: 'approve-setting',
  props: {
    options: {
      type: Array,
      default: () => [],
    },
    approveSetting: {
      type: Object,
      default: () => new TaskApprover(),
    },
  },
  filters: {
  },
  data() {
    return {
      isOpenData
    }
  },
  methods: {
    /** 选择审批等级 */
    switchLevel(val) {
      let multiApproveSetting = [];
      if (val > 1) {
        for (let i = 0; i < val - 1; i++) {
          if (this.approveSetting.multiApproveSetting && this.approveSetting.multiApproveSetting[i]) {
            multiApproveSetting.push(
              this.approveSetting.multiApproveSetting[i]
            );
          } else {
            multiApproveSetting.push({
              leader: '',
              approves: [],
            });
          }
        }

        this.approveSetting.multiApproveSetting = multiApproveSetting;
      }
    },
    getApproverNames(approves) {
      return (approves|| []).map((item) => item.displayName).join(',');
    },
    getApproverIds(approvers) {
      return approvers.map((item) => item.staffId);
    },
    /**
     * 更新审批设置
     *
     * @param {string} key 更新的key值
     * @param {string} value 更新值
     * @param {number} level 更新审批的层级
     */
    updateApproveSetting(key, value, level) {
      let approveSetting = _.cloneDeep(this.approveSetting);

      // 一级设置
      if (level <= 1) {
        approveSetting[key] = value;
        if (approveSetting.leader !== 'users') {
          approveSetting.approves = [];
        }
      }
      // 多级设置
      if (level > 1) {
        let multiApproveSetting = approveSetting.multiApproveSetting[level - 2];
        multiApproveSetting[key] = value;
        if (multiApproveSetting.leader !== 'users') {
          multiApproveSetting.approves = [];
        }
      }
      this.$emit('change', approveSetting);
    },
    /**
     * 选择指定的审批人员
     * @param {number} level 审批的层级
     */
    selectApproveUser(level) {
      let selected = level < 2
        ? this.approveSetting.approves
        : this.approveSetting.multiApproveSetting[level - 2].approves;
      
      let options = {
        title: '选择审批人', // [选填] 默认值为 '请选择人员'
        max: 14, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        mode: BaseSelectUserModeEnum.Filter,
      };

      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0) return;
          
          this.updateApproveSetting('approves', res.data.users, level);
        })
        .catch((err) => {
          console.warn(err);
        });
    },

    formatNumToCN(num) {
      let changeNum = [
        this.$t('common.base.number0'),
        this.$t('common.base.number1'),
        this.$t('common.base.number2'),
        this.$t('common.base.number3'),
        this.$t('common.base.number4'),
        this.$t('common.base.number5'),
        this.$t('common.base.number6'),
        this.$t('common.base.number7'),
        this.$t('common.base.number8'),
        this.$t('common.base.number9'),
      ];

      return changeNum[num];
    },
  },
};
</script>

<style lang="scss" scoped>
// 企微端样式
@import '@src/modules/setting/openData.scss';

.setting-approve {
  &-people {
    line-height: 40px;
    margin-bottom: 12px;
    font-size: 14px;
    color: #999999;
  }
}

.ml-12 {
  margin-left: 12px;
}

.mt-12 {
  margin-top: 12px;
}

.mb-12 {
  margin-bottom: 12px;
}

.w-187 {
  width: 187px;
}
.block-inline {
  display: inline-block;
}
.setting-approve-people {
  display: flex;
  align-items: center;
  ::v-deep .el-select{
    width: 300px;
  }
  .el-input{
    width: 300px;
    .el-input__inner{
      width: 300px;
    }
  }
  line-height: 20px;
}
.approve-radio-group {
  margin: 16px 0;
}
.one-level-approve {
  margin-bottom: 8px;
}
.more-level-approve {
  margin: 16px 0 8px 0;
}
</style>

<style lang="scss">
.setting-approve {
  .el-radio-group {
    margin-bottom: 5px;
  }
}
.setting-approve-people {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin: 0px !important;
}
</style>